import React, { Component } from 'react';
import moment from 'moment'; //time格式工厂
import style from './TenantManage.less';
import { connect } from 'dva';
import { FormattedMessage, formatMessage } from 'umi/locale'; //此方法引入的数据可以在src/locales中配置
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; //头部的那个版块的东西
import ModalBoxForm from './ModalBox';
import Link from 'umi/link';
import {
  Input,
  DatePicker,
  Form,
  Row,
  Col,
  Card,
  PageHeader,
  Alert,
  message,
  Icon,
  Divider, Empty,
} from 'antd';
import {Select,Button , Table ,Modal,Pagination} from '@/components/CustomAntd'
//日期插件
const { MonthPicker, RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

//表单
const FormItem = Form.Item;

//所属租户选择框
const Option = Select.Option;

//页头&&面包屑
const routes = [
  {
    path: 'index',
    breadcrumbName: 'First-level Menu',
  },
  {
    path: 'first',
    breadcrumbName: 'Second-level Menu',
  },
  {
    path: 'second',
    breadcrumbName: 'Third-level Menu',
  },
];

//命名空间
const namespace = 'TenantManage';

const mapStateToProps = function(state) {
  const dataSource = state[namespace].dataSource;

  return {
    dataSource: dataSource, //全部数据
    dataList: dataSource ? dataSource.data.list : [], //专门给表格使用的
    total_elements: dataSource ? dataSource.total_elements : 0,
    // dataList: []
  };
};

const mapDispatchToProps = function(dispatch) {
  return {
    dispatch: dispatch,
  };
};

@connect(
  mapStateToProps,
  mapDispatchToProps,
)
@Form.create()
class TenantManage extends Component {
  componentDidMount() {
    //页面加载前申请一次内容
    const mountLoad = {
      page_size: 10,
      page_num: 1,
    };
    const action = {
      type: `${namespace}/selectBegin`,
      payload: mountLoad,
    };

    const { dispatch } = this.props;
    dispatch(action);
  }

  state = {
    //分页相关状态
    page_size: 10,
    page_num: 1,
    //模态框相关状态
    loading: false,
    visible: false,
    //编辑内容状态
    nowRow: null,
    //新增&编辑标识符
    modalFlag: 'new',
    //搜索表单状态
    searchFormNow: null,
  };

  //编辑
  editList(values) {
    this.setState({
      visible: true,
      nowRow: values,
      modalFlag: 'edit',
    });
  }

  //编辑
  showDetail(values) {
    this.setState({
      visible: true,
      nowRow: values,
      modalFlag: 'detail',
    });
  }

  //删除处理
  deleteList(id) {
    const props = this.props;
    const _this = this;
    const params ={
      ..._this.state.searchFormNow,
    }
    if (params && params.create_time && params.create_time.length > 0) {
      params.created_time_from = moment(params.create_time[0]).format('YYYY-MM-DD HH:mm:00');
      params.created_time_to = moment(params.create_time[1]).format('YYYY-MM-DD HH:mm:59');
    } else {
      delete params.create_time
    }
    delete params.create_time
    Modal.confirm({
      title: '确认删除吗',
      content: '您确定要删除这条数据吗？',
      okText: '确认',
      cancelText: '取消',
      icon: 'frown',
      onOk() {
        //发送删除请求
        props.dispatch({
          type: `${namespace}/deleteBegin`,
          payload: {
            tenant_id: id,
          },
          callback: res => {
            if (res.return_code === 'SUCCESS') {
              message.success('删除成功');
            }
            //代入当前分页状态重新查询一次
            props.dispatch({
              type: `${namespace}/selectBegin`,
              payload: {
                page_size: _this.state.page_size,
                page_num: _this.state.page_num,
                ...params,
              },
            });
          },
        });
      },
      onCancel() {
        return false;
      },
    });
  }

  //子模态框组件修改state保持模态框关闭方法
  childModalChangeModalState() {
    this.setState({
      visible: false,
    });
  }

  //关闭-模态框
  handleCancel = () => {
    this.setState({ visible: false });
  };

  //显示-模态框
  showModal = () => {
    this.setState({
      modalFlag: 'new',
      visible: true,
    });
  };

  //关闭详情模态框
  closeDatails = () => {
    this.setState({
      datailsState: false,
      nowRow: null,
    });
  };

  //搜索时重置分页页数的方法
  changePage = values => {
    //把分页条件放入state
    this.setState({
      searchFormNow: values,
    });
    this.setState({
      page_num: 1,
    });
  };

  //新增后，将state中的页码状态复位 清空搜索表单状态
  clearSearchForm = () => {
    this.setState({
      page_num: 1,
      searchFormNow: null,
    });
    //清空表单
    this.clearNow();
  };

  //父组件操作子组件清空的方法
  onRef = ref => {
    this.child = ref;
  };

  clearNow = e => {
    this.child.handleReset();
  };

  //设置标识符为新建标识符并且显示模态框
  changeFlag = () => {
    this.setState({
      visible: true,
      modalFlag: 'new',
    });
  };

  //表格分页监听函数
  tableChange = (pagination, filters, sorter) => {
    const lastSearch = {
      ...this.props.dataSource.searchQ,
    };

    //这个步骤是为了在有查询条件的时候不会丢掉查询条件
    const params = {
      ...this.props.dataSource.searchQ,
      page_num: pagination.current,
      page_size: pagination.pageSize,
    };

    const action = {
      type: `${namespace}/selectBegin`,
      payload: params,
    };
    const { dispatch } = this.props;
    dispatch(action);
  };

  render() {
    const { pagination } = this.props;

    //列  列名   列名
    const columns = [
      {
        title: formatMessage({ id: 'iot.tenantmanage.tenantmanage_list.tenant_name' }),
        dataIndex: 'tenant_name',
        render: (text, record) => {
          return <a onClick={() => this.showDetail(record)}>{record.tenant_name}</a>;
          /*return <Link to={`/dashboard/tenantDashboard?tenant_id=${record.tenant_id}`}>{record.tenant_name}</Link>;*/
        },
        align: 'center',
      },
      {
        title: formatMessage({ id: 'iot.tenantmanage.tenantmanage_list.tenant_type' }),
        dataIndex: 'tenant_type',
        align: 'center',
        render: (text, record) => {
          if (record.tenant_type == 1) {
            return formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_yh' });
          }
          if (record.tenant_type == 2) {
            return formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_yy' });
          }
        },
      },
      {
        title: formatMessage({ id: 'iot.tenantmanage.tenantmanage_list.contact' }),
        dataIndex: 'contact',
        align: 'center',
      },
      {
        title: formatMessage({ id: 'iot.tenantmanage.tenantmanage_list.contact_num' }),
        dataIndex: 'contact_num',
        align: 'center',
      },

      {
        title: formatMessage({ id: 'iot.tenantmanage.tenantmanage_list.create_time' }),
        dataIndex: 'create_time',
        align: 'center',
      },
      {
        title: '操作',
        dataIndex: 'doIt',
        key: 'doIt',
        width: 120,
        render: (text, record) => (
          <span className="table-operation">
            <a onClick={() => this.editList(record)}>编辑</a>
            <Divider type="vertical"/>
            <a onClick={() => this.deleteList(record.tenant_id)}>删除</a>
          </span>
        ),
        align: 'center',
      },
    ];

    //分页配置项
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: Number(this.props.dataSource ? this.props.dataSource.data.total_elements : 0), //读取总数据数
      current: Number(this.props.dataSource ? this.props.dataSource.data.page_num : 1), //当前页数
      showTotal: total => `共有 ${parseInt(total)} 条数据 当前第${this.state.page_num}页`,
      onChange: (page, pageSize) => {
        this.setState({
          page_num: page,
          page_size: pageSize,
        });
      },
      onShowSizeChange: (current, size) => {
        this.setState({
          page_num: current,
          page_size: size,
        });
      },
      ...pagination,
    };

    return (

      <PageHeaderWrapper>
        <div
          style={{
            backgroundColor: '#FFFFFF',
            paddingLeft: '5%',
            paddingRight: '5%',
          }}
        >
          <div>
            {/* 查询表单部分 */}
            <TheNewForm
              dispatch={this.props.dispatch}
              showModal={this.showModal}
              changeFlag={this.changeFlag}
              changePage={this.changePage}
              onRef={this.onRef}
            />
            {/* 渲染列表部分 */}
            {
              this.props.dataList && this.props.dataList.length > 0 ?
                <Table
                  dataSource={this.props.dataList}
                  columns={columns}
                  rowKey={record => record.tenant_id}
                  onChange={this.tableChange}
                  pagination={paginationProps}
                  onShowSizeChange={this.onShowSizeChange}
                  reMess={this.state.reMess}
                  delMess={this.state.delMess}
                />
                :
                <Empty
                  style={{ paddingBottom: 30, paddingTop: 15 }}
                />
            }
            {/* 模态框部分 */}
            {this.state.visible ? (
              <ModalBoxForm
                visible={this.state.visible}
                dispatch={this.props.dispatch}
                page_size={this.state.page_size}
                cancel={this.handleCancel}
                loading={this.state.loading}
                childModalChangeModalState={this.childModalChangeModalState.bind(this)}
                addMess={this.state.addMess}
                nowRow={this.state.nowRow}
                modalFlag={this.state.modalFlag}
                page_num={this.state.page_num}
                searchFormNow={this.state.searchFormNow}
                clearSearchForm={this.clearSearchForm}
              />
            ) : (
              []
            )}
          </div>
        </div>
      </PageHeaderWrapper>


    );
  }
}

export default TenantManage;

//创建高阶表单组件
class NewForm extends Component {
  componentDidMount() {
    this.props.onRef(this);
  }

  //表单重置
  handleReset = () => {
    this.props.form.resetFields();
  };

  //查询表单方法
  query = e => {
    const { dispatch } = this.props;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const valuesEnd = {
          page_size: 10,
          page_num: 1,
        };
        if (values.tenant_name) {
          valuesEnd.tenant_name = values.tenant_name;
        }
        if (values.create_time && values.create_time.length > 0) {
          valuesEnd.created_time_from = moment(values.create_time[0]).format('YYYY-MM-DD HH:mm:00');
          valuesEnd.created_time_to = moment(values.create_time[1]).format('YYYY-MM-DD HH:mm:59');
        }
        this.props.changePage(values);
        dispatch({
          type: `${namespace}/selectBegin`,
          payload: valuesEnd,
        });
      }
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    // alert(this.dataSource.total_elements)

    //规则就是用来打破的
    const projectName_rules = {
      rules: [
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能输入空格',
        },
      ],
    };
    const createTime_rules = {
      rules: [],
    };
    const tenant_rules = {
      // initialValue: null,
    };

    return (
      <Form onSubmit={this.query} layout="inline">
        <div
          style={{
            fontSize: '16px',
            marginBottom: '15px',
          }}
        >
          <div style={{ height: 60 }}>
            <Row align="middle">
              <Col xl={12} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>{formatMessage({ id: 'iot.tenantmanage.tenantmanage_list.tenant_name' })} :
                </div>
                {getFieldDecorator('tenant_name')(<Input placeholder="请输入" style={{ width: '65%' }}/>)}
              </Col>
              <Col lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>{formatMessage({ id: 'iot.tenantmanage.tenantmanage_list.create_time' })} :
                </div>
                {getFieldDecorator('create_time')(
                  <RangePicker
                    placeholder={['开始日期', '结束日期']}
                    showTime={{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] }}
                    format="YYYY-MM-DD HH:mm:00"
                    onChange={this.queryCreate}
                    style={{ width: '65%' }}
                  />)}
              </Col>
            </Row>
          </div>
          <Row gutter={30}>
            <Col md={18} sm={24} align="left" style={{ paddingLeft: 10 }}>
              <span>
                  <Button type="primary" onClick={this.props.showModal}>
                    新建
                  </Button>
                </span>
            </Col>
            <Col md={6} sm={24} align="right" style={{ paddingLeft: 10 }}>
               <span>
                  <Button type="primary" htmlType="submit">查询</Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>重置</Button>
               </span>
            </Col>
          </Row>
        </div>
      </Form>

    );
  }
}

const TheNewForm = Form.create({ name: 'time_related_controls' })(NewForm);
